package com.lemon.smartsafetynew.ui.activity.hidden;

import android.os.Bundle;
import android.text.InputFilter;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lemon.android.http.LemonRequestParams;
import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppManager;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.app.Constants;
import com.lemon.smartsafety.entity.event.http.HttpCallbackEvent;
import com.lemon.smartsafety.http.callback.HandlerCallback;
import com.lemon.smartsafetynew.ui.activity.base.PhotoSelectBaseActivity;
import com.lemon.smartsafety.ui.adapter.common.SelectEvidenceAdapter;
import com.lemon.smartsafety.utils.app.HUDUtil;
import com.lemon.smartsafety.utils.app.UIHelper;
import com.lemon.smartsafety.utils.common.StringUtils;
import com.lemon.smartsafetynew.entity.User;
import com.lemon.smartsafetynew.entity.common.NetResultBo;
import com.lemon.smartsafetynew.entity.contact.DepartmentVo;
import com.lemon.smartsafetynew.entity.contact.PersonVo;
import com.lemon.smartsafetynew.entity.event.common.ViewEvent;
import com.lemon.smartsafetynew.entity.event.contact.DepartmentEvent;
import com.lemon.smartsafetynew.entity.event.contact.PersonEvent;
import com.lemon.smartsafetynew.entity.hidden.RectifySafeHiddenDto;
import com.lemon.smartsafetynew.entity.hidden.SafeHiddenDownloadVo;
import com.lemon.smartsafetynew.net.services.SafeHiddenServices;
import com.lemon.smartsafetynew.ui.activity.contact.DepartmentListActivity;
import com.lemon.smartsafetynew.ui.activity.contact.PersonListActivity;
import com.lemon.smartsafetynew.util.common.CommonUtil;
import com.lemon.smartsafetynew.util.common.PointLengthFilter;
import com.lemon.smartsafetynew.util.constants.KeyConstants;
import com.lemon.smartsafetynew.util.constants.SafeCloudConstants;
import com.lemon.smartsafetynew.util.constants.TimeFormatConstants;
import com.lemon.smartsafetynew.util.user.AccountUtil;
import com.rengwuxian.materialedittext.MaterialEditText;
import com.wdullaer.materialdatetimepicker.date.DatePickerDialog;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 整改隐患
 * Created by Andrew on 2017/9/11.
 */

public class SafeHiddenRectifyAndReformActivity extends PhotoSelectBaseActivity {

    @Bind(R.id.hidden_submit_btn)
    Button hiddenSubmitBtn;
    @Bind(R.id.hidden_responsible_tv)
    TextView hiddenResponsibleTv;
    @Bind(R.id.hidden_responsible_department_tv)
    TextView hiddenResponsibleDepartmentTv;
    @Bind(R.id.hidden_real_finish_time_tv)
    TextView hiddenRealFinishTimeTv;
    @Bind(R.id.rectify_and_reform_money_et)
    EditText rectifyAndReformMoneyEt;
    @Bind(R.id.rectify_and_reform_remark_et)
    MaterialEditText rectifyAndReformRemarkEt;
    @Bind(R.id.review_department_tv)
    TextView reviewDepartmentTv;
    @Bind(R.id.review_person_tv)
    TextView reviewPersonTv;

    private static SafeHiddenDownloadVo safeHiddenDownloadVo;


    /**
     * 部门
     */
    private DepartmentVo departmentVo;

    /**
     * 人员
     */
    private PersonVo personVo;

    private User user;
    //每次提交唯一ID
    private String UUID = "";

    @Override
    protected void getBundleArgs() {
        super.getBundleArgs();

        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            if (bundle.containsKey(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO)) {
                safeHiddenDownloadVo = (SafeHiddenDownloadVo) bundle.getSerializable(KeyConstants.KEY_SAFE_HIDDEN_DOWNLOAD_VO);
            }
        }

    }

    @Override
    protected void initTitle() {
        this.setBarTitle("隐患整改");
    }

    @Override
    protected void callFinish() {
        //退出此页面都要刷新一下HiddenDangerDto
        AppService.getBus().post(new ViewEvent(SafeHiddenRectifyAndReformActivity.class.getName()));
        AppManager.getAppManager().finishActivity(SafeHiddenRectifyAndReformActivity.this);
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_safe_hidden_rectify_and_reform;
    }

    @Override
    protected void initViews() {
        super.initViews();

        initData();
        initCommon();
    }

    /**
     * 初始化
     */
    private void initCommon() {

        hiddenResponsibleTv.setText(safeHiddenDownloadVo.getRectify_user_name());
        hiddenResponsibleDepartmentTv.setText(safeHiddenDownloadVo.getRectify_dept());

        rectifyAndReformMoneyEt.setFilters(new InputFilter[]{new PointLengthFilter()}); //设置输入金额最小单位为分

        //hiddenRealFinishTimeTv.setText(CommonUtil.secondToTimeStr(System.currentTimeMillis(), DateTypeEnum.DAY));
    }

    /**
     * 初始化
     */
    private void initData() {
        UUID = CommonUtil.getUUID();
        user = AccountUtil.getUser();
    }

    /**
     * 验证表单
     */
    private boolean verifyParam() {

//        if (StringUtils.isEmpty(hiddenRealFinishTimeTv.getText().toString().trim())) {
//            mHUDUtil.showErrorTip("请选择实际完成时间");
//            return false;
//        }

        if (StringUtils.isEmpty(rectifyAndReformMoneyEt.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请输入实际整改金额");
            return false;

        } else {

            String str = rectifyAndReformMoneyEt.getText().toString().trim();

            Pattern r = Pattern.compile(SafeCloudConstants.MONEY_INPUT_REGULAR_EXPRESSION);
            Matcher m = r.matcher(str);

            if (m.matches()) {
                //return true;
            } else {
                mHUDUtil.showErrorTip("输入的实际整改金额超过最大值。");
                return false;
            }

        }

        if (StringUtils.isEmpty(rectifyAndReformRemarkEt.getText().toString().trim())) {
            mHUDUtil.showErrorTip("请输入整改措施");
            return false;
        }

        //disable by Andrew.yin 2017/10/25 begin
//        if (StringUtils.isEmpty(reviewDepartmentTv.getText().toString().trim())) {
//            mHUDUtil.showErrorTip("请选择复查部门");
//            return false;
//        }
//
//        if (StringUtils.isEmpty(reviewPersonTv.getText().toString().trim())) {
//            mHUDUtil.showErrorTip("请选择复查人员");
//            return false;
//        }
        //disable by Andrew.yin 2017/10/25 end

        return true;

    }


    @OnClick({R.id.hidden_submit_btn, R.id.real_finish_time_layout, R.id.review_department_layout, R.id.review_person_layout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.hidden_submit_btn:
                hiddenSubmitBtn.setEnabled(false);
                if (verifyParam()) {
                    rectify();
                } else {
                    hiddenSubmitBtn.setEnabled(true);
                }
                break;
            case R.id.real_finish_time_layout:
                //pickCheckDate();
                break;
            case R.id.review_department_layout:
                showDepartmentList();
                break;
            case R.id.review_person_layout:
                if (departmentVo != null) {
                    showPersonList();
                } else {
                    mHUDUtil.showErrorTip("请先选择责任部门！");
                }
                break;
        }
    }

    /**
     * 上传整改信息
     */
    private void rectify() {

        mHUDUtil.showHUD();

        final LemonRequestParams params = new LemonRequestParams("");

        RectifySafeHiddenDto rectifySafeHiddenDto = new RectifySafeHiddenDto();
        rectifySafeHiddenDto.setDanger_id(safeHiddenDownloadVo.getId());
        rectifySafeHiddenDto.setRectify_user_id(user.getUserId());
        rectifySafeHiddenDto.setRectify_user_name(user.getUserName());
        rectifySafeHiddenDto.setRectify_money(rectifyAndReformMoneyEt.getText().toString().trim());
        rectifySafeHiddenDto.setRectify_content(rectifyAndReformRemarkEt.getText().toString().trim());
        //rectifySafeHiddenDto.setReview_user_id(personVo.getUser_id());
        //rectifySafeHiddenDto.setReview_dept(reviewDepartmentTv.getText().toString().trim());
        rectifySafeHiddenDto.setReview_user_id(safeHiddenDownloadVo.getReview_user_id());

        params.put("data", mGson.toJson(rectifySafeHiddenDto));
        params.put("submit_uuid", UUID);

        ExecutorService fixedThreadPool = Executors.newSingleThreadExecutor();
        fixedThreadPool.execute(new Runnable() {
            @Override
            public void run() {

                getUploadMediaItems(new SelectEvidenceAdapter.CropCallBack<Map<String, File>>() {
                    @Override
                    public void onStart() {

                    }

                    @Override
                    public void onFinish(Map<String, File> data) {

                        if (data.isEmpty()) {    //无附件

                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    hiddenSubmitBtn.setEnabled(true);
                                    mHUDUtil.showErrorTip("整改操作必须添加附件。");
                                }
                            });

                        } else {                //有附件
                            SafeHiddenServices
                                    .init()
                                    .rectifyHidden(params, data);
                        }

                    }
                });
            }
        });

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(HttpCallbackEvent event) {
        if (KeyConstants.URL_RECTIFY_SAFE_HIDDEN.equals(event.getTag())) {                           //整改隐患 有附件
            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {

            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                hiddenSubmitBtn.setEnabled(true);
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    mHUDUtil.showDoneTip("提交成功", new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    if (event.getCode() == NetResultBo.Code.REPEAT_SUBMIT.getCode()) {
                        //此处为过滤重复提交的错误，此错误不需要做任何提示

                    } else {
                        mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {

                            }
                        });
                    }

                }
            }
        } else if (KeyConstants.URL_RECTIFY_SAFE_HIDDEN_NO_FILE.equals(event.getTag())) {            //整改隐患 无附件

            if (HandlerCallback.HttpFlow.START == event.getHttpFlow()) {

            } else if (HandlerCallback.HttpFlow.FINISH == event.getHttpFlow()) {
                mHUDUtil.hidden();
                hiddenSubmitBtn.setEnabled(true);
                if (Constants.Result.SUCCESS == event.getEventResult()) {

                    mHUDUtil.showDoneTip("提交成功", new HUDUtil.CallBack() {
                        @Override
                        public void onCall() {
                            callFinish();
                        }
                    });
                } else if (Constants.Result.ERROR == event.getEventResult()) {

                    if (event.getCode() == NetResultBo.Code.REPEAT_SUBMIT.getCode()) {
                        //此处为过滤重复提交的错误，此错误不需要做任何提示

                    } else {
                        mHUDUtil.showErrorTip(event.getMsg(), new HUDUtil.CallBack() {
                            @Override
                            public void onCall() {

                            }
                        });
                    }

                }
            }
        }
    }

    /**
     * 选择实际整改日期
     */
    private void pickCheckDate() {
        Calendar now = Calendar.getInstance();
        DatePickerDialog dpd = DatePickerDialog.newInstance(new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePickerDialog view, int year, int monthOfYear, int dayOfMonth) {

                Calendar calendar = Calendar.getInstance();
                calendar.set(year, monthOfYear, dayOfMonth);
                SimpleDateFormat dateFormat = new SimpleDateFormat(TimeFormatConstants.FORMAT_DATE, Locale.getDefault());
                String dateStr = dateFormat.format(calendar.getTime());

                hiddenRealFinishTimeTv.setText(CommonUtil.avoidNullString(dateStr));

            }
        }, now.get(Calendar.YEAR), now.get(Calendar.MONTH), now.get(Calendar.DAY_OF_MONTH));
        dpd.setThemeDark(false);
        dpd.vibrate(false);
        dpd.show(getFragmentManager(), Constants.DIALOG_TAG_CHECK_DATE);
    }


    /**
     * 选择部门
     */
    private void showDepartmentList() {
        Bundle bundle = new Bundle();
        bundle.putString(KeyConstants.KEY_TAG, SafeHiddenRectifyAndReformActivity.class.getName());
        UIHelper.showActivity(SafeHiddenRectifyAndReformActivity.this, bundle, DepartmentListActivity.class);
    }

    /**
     * 选择人员
     */
    private void showPersonList() {
        Bundle bundle = new Bundle();
        bundle.putSerializable(KeyConstants.KEY_DEPARTMENT, departmentVo);
        bundle.putString(KeyConstants.KEY_TAG, SafeHiddenRectifyAndReformActivity.class.getName());
        UIHelper.showActivity(SafeHiddenRectifyAndReformActivity.this, bundle, PersonListActivity.class);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDepartmentEvent(DepartmentEvent event) {

        if (SafeHiddenRectifyAndReformActivity.class.getName().equals(event.getTag())) {
            departmentVo = event.getDepartmentVo();
            reviewDepartmentTv.setText(CommonUtil.avoidNullString(departmentVo.getName()));
            reviewPersonTv.setText("");
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPersonEvent(PersonEvent event) {

        if (SafeHiddenRectifyAndReformActivity.class.getName().equals(event.getTag())) {
            personVo = event.getPersonVo();
            reviewPersonTv.setText(CommonUtil.avoidNullString(personVo.getUser_name()));
        }
    }


}
